package com.qili.controller;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.controller.BaseController;
import com.qili.base.entity.CurrentUser;
import com.qili.entity.exam.ExStuExamCopy;
import com.qili.entity.exam.dto.ExExamDTO;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.sys.SysMenu;
import com.qili.entity.sys.SysUser;
import com.qili.exception.MyException;
import com.qili.mapper.exam.ExExamMapper;
import com.qili.mapper.exam.ExStuExamCopyMapper;
import com.qili.service.SysUserService;
import com.qili.service.exam.ExExamService;
import com.qili.service.search.SearchIndexService;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
* @Author:zhaoyongke
* @Description: 综合考试系统
* @Date:10:46 2021/8/6
*/
@Controller
@Slf4j
@RequestMapping("/synthesize")
public class IndexController extends BaseController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SupervisorFileService supervisorFileService;
    @Autowired
    ExExamService exExamService;
    @Autowired
    ExExamMapper exExamMapper;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    ExStuExamCopyMapper exStuExamCopyMapper;


    @GetMapping(value ="/index")
    public String index(Model model, HttpServletRequest request){
        //带出用户头像姓名
        CurrentUser currentUser = CommonUtil.getUser();
        String userId=CommonUtil.getUserId();
        SysUser sysUser=sysUserService.selectByPrimaryKey(userId);
        if(sysUser==null){
            // 跳转到登陆页面
            request.setAttribute("type","login");
            return "/login";
        }
        // 个人中心设置的数量
        String tagnum=sysUser.getNumTag();
        currentUser.setNumTag(tagnum);
        String AsTags = currentUser.getTags();
        String[] AyTags;
        if (StringUtil.isNotBlank(AsTags)  &&  StringUtil.isNotBlank(tagnum) ) {
            String[] newAyTags=new String[Integer.valueOf(tagnum)];
            AyTags = AsTags.split(";");
            int  length=AyTags.length;
            if(Integer.valueOf(tagnum)<length){
                //清除多余的0
                for (int i = 0; i < length; i++) {
                    if(i<Integer.valueOf(tagnum)){
                        newAyTags[i]=AyTags[i];
                    }
                }
                currentUser.setTags( StringUtils.join(newAyTags, ";") + ";");
            }
        }
        Session session = com.qili.core.shiro.Principal.getSession();
        session.setAttribute("currentPrincipal", currentUser);
        SupervisorFile supervisorFile =  supervisorFileService.getPersonalImg(userId);
        request.setAttribute("file", supervisorFile);
        //区分综合服务  有角色走管理端 没有走客户端
        List<String> roles = CommonUtil.getUserRoleList();
        if(roles.indexOf("ksgly")!=-1){
            return "/synthesize/index";
        }else{
            return examination(model);
        }
    }

    /**
    * @Description:客户端
    * @param model
    * @Date:17:23 2021-08-24
    */
    public String examination(Model model){
        //获取当前登录人
        CurrentUser user = CommonUtil.getUser();
        model.addAttribute("userName",user.getRealName());
        //查询正式考试
        ExExamDTO zsExam=new ExExamDTO();
        //查询已提交的考试
        zsExam.setStatus("002");
        //查询考试模式为正式考试
        zsExam.setType("001");
        zsExam.setUserId(user.getId());
        Integer zsList=selectExamList(zsExam);
        model.addAttribute("zs",zsList);

        //查询测试考试
        ExExamDTO csExam=new ExExamDTO();
        //查询已提交的考试
        csExam.setStatus("002");
        //查询考试模式为测试考试
        csExam.setType("002");
        csExam.setUserId(user.getId());
        Integer csList=selectExamList(csExam);
        model.addAttribute("cs",csList);

        //个人考试
        Integer grks =selectExamResult("001",user.getId(),"1");
        model.addAttribute("grks",grks);
        //个人练习
        Integer grlx =selectExamResult("002",user.getId(),"0");
        model.addAttribute("grlx",grlx);
        return "/examination/index";
    }

    /**
     * @Description:查询考试数据
     * @param exam
     * @Date:15:18 2021-08-24
     */
    public Integer selectExamList(ExExamDTO exam){
        List<ExExamDTO>  ksList =new ArrayList<>();
        try {
            ksList = exExamMapper.selectExamList(exam);
        } catch (MyException e) {
            e.printStackTrace();
        }
        if(ksList!=null && ksList.size()>0){
            return ksList.size();
        }else{
            return 0;
        }

    }

    /**
    * @Description:正式考试
    * @param exam
        * @param page
        * @param limit
    * @Date:14:08 2021-09-15
    */
    @RequestMapping(value = "/seleExam")
    @ResponseBody
    public ReType seleExam(ExExamDTO exam, int page, int limit){
        List<ExExamDTO> ksList = new ArrayList<>();
        Page<ExExamDTO> tPage = PageHelper.startPage(page, limit);
        try {
            exam.setType("001");
            exam.setUserId(CommonUtil.getUserId());
            exam.setStatus("002");
            ksList = exExamMapper.selectExamList(exam);
//            String endTime = exam.getEndTime();
//            String currentDateString = DateUtil.getCurrentDateString();
//            for (int i = 0; i < ksList.size(); i++) {
//                int li = DateUtil.compareToDate(currentDateString, endTime, "yyyy-MM-dd HH:mm:ss");
//                if (li == 1) {
//                    ksList.get(i).setState("0");
//                } else {
//                    ksList.get(i).setState("1");
//                }
//
//            }
            //获取封面的url
            if(ksList!=null&&ksList.size()>0){
                for(int i=0;i<ksList.size();i++){
                    SupervisorFile supervisorFile=new SupervisorFile();
                    supervisorFile.setProjectId(ksList.get(i).getExamId());
                    supervisorFile.setType("0819");
                    SupervisorFile file=supervisorFileService.selectOne(supervisorFile);
                    if(file!=null) {
                        ksList.get(i).setUrl(url(file.getUrl()));
                    }
                }
            }
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), ksList);
    }

    /**
     * @Description:练习
     * @param exam
     * @param page
     * @param limit
     * @Date:14:08 2021-09-15
     */
    @RequestMapping(value = "/seleTestExam")
    @ResponseBody
    public ReType seleTestExam(ExExamDTO exam, int page, int limit){
        List<ExExamDTO> ksList = new ArrayList<>();
        Page<ExExamDTO> tPage = PageHelper.startPage(page, limit);
        try {
            exam.setType("002");
            exam.setUserId(CommonUtil.getUserId());
            exam.setStatus("002");
            ksList = exExamMapper.selectExamList(exam);
//            String endTime = exam.getEndTime();
//            String currentDateString = DateUtil.getCurrentDateString();
//            for (int i = 0; i < ksList.size(); i++) {
//                int li = DateUtil.compareToDate(currentDateString, endTime, "yyyy-MM-dd HH:mm:ss");
//                  if (li == 1){
//                      ksList.get(i).setState("0");
//                  }else{
//                      ksList.get(i).setState("1");
//                  }
//            }
           // DateUtil.getCurrentDateString()
            //获取封面的url
            if(ksList!=null&&ksList.size()>0){
                for(int i=0;i<ksList.size();i++){
                    SupervisorFile supervisorFile=new SupervisorFile();
                    supervisorFile.setProjectId(ksList.get(i).getExamId());
                    supervisorFile.setType("0819");
                    SupervisorFile file=supervisorFileService.selectOne(supervisorFile);
                    if(file!=null) {
                        ksList.get(i).setUrl(url(file.getUrl()));
                    }
                }
            }
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), ksList);
    }


    /**
     * @Description:个人考试数据数量
     * @param type
     * @param userId
     * @Date:11:19 2021-08-30
     */
    public Integer selectExamResult(String type,String userId,String isMark){
        ExStuExamCopy excopy=new ExStuExamCopy();
        excopy.setType(type);
        excopy.setUserId(userId);
        excopy.setIsMark(isMark);
        List<ExStuExamCopy> examList=exStuExamCopyMapper.selectExamResult(excopy);
        if(examList!=null && examList.size()>0){
            return examList.size();
        }else{
            return 0;
        }
    }

    /**
     * @Description:个人考试
     * @param excopy
     * @param page
     * @param limit
     * @Date:11:19 2021-08-30
     */
    @RequestMapping(value = "/selectStuExam")
    @ResponseBody
    public ReType selectStuExam(ExStuExamCopy excopy, int page, int limit){
        List<ExStuExamCopy> examList=new ArrayList<>();
        Page<ExStuExamCopy> tPage = PageHelper.startPage(page, limit);
        try {
            excopy.setType("001");
            excopy.setUserId(CommonUtil.getUserId());
            excopy.setIsMark("1");
            examList = exStuExamCopyMapper.selectExamResult(excopy);
            //获取封面的url
            if(examList!=null&&examList.size()>0){
                for(int i=0;i<examList.size();i++){
                    SupervisorFile supervisorFile=new SupervisorFile();
                    supervisorFile.setProjectId(examList.get(i).getExamId());
                    supervisorFile.setType("0819");
                    SupervisorFile file=supervisorFileService.selectOne(supervisorFile);
                    if(file!=null) {
                        examList.get(i).setUrl(url(file.getUrl()));
                    }
                }
            }
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), examList);
    }

    /**
     * @Description:个人练习
     * @param excopy
     * @param page
     * @param limit
     * @Date:11:19 2021-08-30
     */
    @RequestMapping(value = "/selectStuTestExam")
    @ResponseBody
    public ReType selectStuTestExam(ExStuExamCopy excopy, int page, int limit){
        List<ExStuExamCopy> examList=new ArrayList<>();
        Page<ExStuExamCopy> tPage = PageHelper.startPage(page, limit);
        try {
            excopy.setType("002");
            excopy.setUserId(CommonUtil.getUserId());
            excopy.setIsMark("0");
            examList = exStuExamCopyMapper.selectExamResult(excopy);
            //获取封面的url
            if(examList!=null&&examList.size()>0){
                for(int i=0;i<examList.size();i++){
                    SupervisorFile supervisorFile=new SupervisorFile();
                    supervisorFile.setProjectId(examList.get(i).getExamId());
                    supervisorFile.setType("0819");
                    SupervisorFile file=supervisorFileService.selectOne(supervisorFile);
                    if(file!=null) {
                        examList.get(i).setUrl(url(file.getUrl()));
                    }
                }
            }
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), examList);
    }




    /**
    * @Description:考试结果
    * @param excopy
        * @param page
        * @param limit
    * @Date:11:19 2021-08-30
    */
    @GetMapping("/selectExamResult")
    @ResponseBody
    public ReType selectExamResult(ExStuExamCopy excopy, int page, int limit){
        List<ExStuExamCopy> examList=new ArrayList<>();
        Page<ExStuExamCopy> tPage = PageHelper.startPage(page, limit);
        try {
            excopy.setType("001");
            excopy.setUserId(CommonUtil.getUserId());
//            excopy.setIsMark("1");
            examList=exStuExamCopyMapper.selectExamResult(excopy);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), examList);
    }
    //图片的url
    public String url(String url){
        String imgUrl = url;
        String uploadPath = uploadUtil.getUploadPath();
        imgUrl = imgUrl.substring(uploadPath.length());
        imgUrl = File.separator+"itfile"+File.separator+imgUrl;
        return imgUrl;
    }
}
